package com.toommi.refuse.listener;

import com.toommi.refuse.annotation.PermissionController;
import com.toommi.refuse.annotation.PermissionReport;
import com.toommi.refuse.entity.PermissionGroup;
import com.toommi.refuse.entity.SysPermission;
import org.springframework.aop.support.AopUtils;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ApplicationReadyEventListener implements ApplicationListener<ApplicationReadyEvent> {


    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
        List<PermissionGroup> permissionGroupList = new ArrayList<>();
        List<String> groupCodeList = new ArrayList<>();
        List<SysPermission> permissionList = new ArrayList<>();

        Map<String, Object> beans = applicationReadyEvent.getApplicationContext().getBeansWithAnnotation(PermissionController.class);
        for (Object bean : beans.values()) {
            Class<?> targetClass = AopUtils.getTargetClass(bean);
            PermissionController annotation = targetClass.getAnnotation(PermissionController.class);
            if (annotation == null) {
                continue;
            } else {
                //判断是否要存贮permissiongroup
                if (!groupCodeList.contains(annotation.groupCode())) {
                    groupCodeList.add(annotation.groupCode());

                    PermissionGroup permissionGroup = new PermissionGroup();
                    permissionGroup.setCode(annotation.groupCode());
                    permissionGroup.setName(annotation.groupName());

                    permissionGroupList.add(permissionGroup);
                }

            }

            Method[] declaredMethods = targetClass.getDeclaredMethods();
            for (Method method : declaredMethods) {
                PermissionReport data = method.getAnnotation(PermissionReport.class);
                if (null != data) {
                    String nameMethod = method.getName();
                    String group = data.group();
                    String name = data.name();
                    String code = data.value();

                    SysPermission sysPermission = new SysPermission();

                    sysPermission.setPerssionCode(code);
                    sysPermission.setPerssionName(name);
                    sysPermission.setGroupCode(group);
                    permissionList.add(sysPermission);
                }
            }

        }
        EventUtil.dispatcher(IPermissionInterface.class, permissionGroupList, permissionList);

    }

}